package com.clementheliou.cheliou.dal.dao.photo.impl;

import java.util.List;

import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.clementheliou.cheliou.dal.dao.generic.impl.GenericHibernateDAO;
import com.clementheliou.cheliou.dal.dao.member.MemberDAO;
import com.clementheliou.cheliou.dal.dao.photo.PhotoDAO;
import com.clementheliou.cheliou.dal.model.base.enumeration.SortOrder;
import com.clementheliou.cheliou.dal.model.photo.Photo;
import com.clementheliou.cheliou.dal.model.photo.dto.PhotoDTO;
import com.clementheliou.cheliou.dal.model.photo.enumeration.PhotoSortableColumn;

/**
 * Hibernate-based implementation of the DAO dedicated to the {@link Photo} entities.
 * 
 * @author Clément HELIOU (clement.heliou@gmail.com)
 * @see {@link GenericHibernateDAO};
 * @see {@link MemberDAO};
 * @see {@link Photo};
 * @see {@link Repository}.
 * @since 1.0
 */
@Repository
public class PhotoHibernateDAO extends GenericHibernateDAO<Photo> implements PhotoDAO {

	/**
	 * SLF4J logger for this class.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(PhotoHibernateDAO.class);

	/**
	 * <i>{@inheritDoc}</i>
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	@Override
	@SuppressWarnings("unchecked")
	public List<PhotoDTO> getLastPhotos(int first, int pageSize, PhotoSortableColumn sortableColumn, SortOrder sortOrder) {
		LOGGER.debug("Get the last photos from the {} index with {} results at the most, ordered by '{}' {}.", first, pageSize, sortableColumn.getColumnName(), sortOrder.getHqlClause());

		final StringBuilder queryString = new StringBuilder("SELECT new ");
		queryString.append(PhotoDTO.class.getName());
		queryString.append("(additionDate, id, code, shootingDate, titleKey) ");
		queryString.append("FROM Photo ");
		queryString.append("ORDER BY ").append(sortableColumn.getColumnName()).append(" ").append(sortOrder.getHqlClause());

		final Query query = getCurrentSession().createQuery(queryString.toString());
		query.setFirstResult(first);
		query.setMaxResults(pageSize);

		return (List<PhotoDTO>) query.list();
	}
}
